package com.zyx.concurrentdemo.c06cas;

import com.zyx.concurrentdemo.c02basic.util.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

import static com.zyx.concurrentdemo.c02basic.util.Sleeper.sleep;

/**
 * @author Yaxi.Zhang
 * @since 2021/10/18 13:03
 * desc: cas实现加锁案例
 */
@SuppressWarnings("AlibabaAvoidManuallyCreateThread")
@Slf4j(topic = "c.TestLockCas")
public class TestLockCas {
    public static void main(String[] args) {
        LockCas lock = new LockCas();
        Thread t1 = new Thread(() -> {
            log.debug("begin...");
            lock.lock();
            try {
                log.debug("lock...");
                sleep(1);
            } finally {
                lock.unlock();
            }
        }, "t1");
        t1.start();
        Sleeper.sleep(2);
        Thread t2 = new Thread(() -> {
            log.debug("begin...");
            lock.lock();
            try {
                log.debug("lock...");
            } finally {
                lock.unlock();
            }
        }, "t2");
        t2.start();

    }
}

@Slf4j(topic = "c.LockCas")
class LockCas {
    /**
     * 锁状态: 0 未加锁 1 加锁
     */
    private final AtomicInteger state = new AtomicInteger(0);

    public void lock() {
        while (true) {
            if (state.compareAndSet(0, 1)) {
                break;
            }
        }
    }

    public void unlock() {
        state.set(0);
        log.debug("unlock");
    }
}
